import axios, { AxiosResponse } from 'axios';

export namespace HTTP {
  export const serverAddr = 'http://localhost:8021';
  const serverTimeout = 5000;

  export interface RequestOption<REQ, RES> {
    method: 'GET' | 'PUT' | 'POST' | 'DELETE';
    path: string;
    data?: REQ;
    resp: (o: AxiosResponse<RES>) => RES;
  }

  export function sendRequest<REQ, RES>(o: RequestOption<REQ, RES>): Promise<RES> {
    return new Promise((resolve, reject) => {
      axios
        .request({
          url: serverAddr + o.path,
          method: o.method,
          data: o.data,
          headers: {
            'Content-Type': 'application/json',
          },
          timeout: serverTimeout,
        })
        .then((res: AxiosResponse<RES>) => resolve(o.resp(res)))
        .catch(reject);
    });
  }
}
